import {getBarcode,getBlock} from "../../utils/block"
var nfc=require("../../utils/nfc");
var _that;
Page({
  data: {
    state:"",barcode:"",block:"",afi:"",iswrite:false,isreplace:false,uid:""
  },
  async nfcRead(uid){
    console.log(uid);
    await nfc.connect();
    if(_that.data.iswrite){
      //await nfc.setAfi(0x07);
      var res=await nfc.setBlock(_that.data.block);
      if(!res){
        wx.showToast({title: '写入失败',icon:"error"});
      }
      else{
        wx.showToast({title: '写入成功',icon:"success"});
      }
      _that.setData({iswrite:false});
      return;
    }
    _that.setData({uid:uid});
    var afi=await nfc.getAfi();
    var block=await nfc.getBlock(0,10);
    if(block[1]==0){
      wx.showToast({title: '未加工标签',icon:"error"});
      this.setData({state:"未加工",afi:afi,block:"", barcode:""});
      return;
    }
    var barcode=getBarcode(block);
    this.setData({state:"已加工",afi:afi,barcode:barcode,block:block.slice(1)});
  },
  onLoad(){
    _that=this;
    nfc.start();
    nfc.onread(this.nfcRead);
  },
  onUnload(){
    console.log("页码关闭");
    nfc.unread();
    nfc.close();
    nfc.stop();
  },
  cancelWhiteBlock(){
    this.setData({iswrite:false,isreplace:true});
  },
  whiteBlock(){
      this.setData({iswrite:true,isreplace:false});
  },
  scanBarcode() {
    wx.scanCode({
      success: (res) => {
        var newbarcode=res.result;
        if(newbarcode==this.data.barcode){
          wx.showToast({title: '无需重复写入相同条码',icon:"error"});
          return;
        }
        var buffer=getBlock(newbarcode);

        this.setData({block:buffer, barcode:newbarcode,isreplace:true});
        
      }
    })
  },
})